package Netty_JBoss;

import Utils.GzipUtils;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.io.File;
import java.io.FileInputStream;

/**
 * Created by brossdong on 2017/12/13.
 */
public class Client {
    public static void main(String[] args)throws Exception {

        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap b = new Bootstrap();
        b.group(group)
                .channel(NioSocketChannel.class)
                //设置日志
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel sc) throws Exception {
                        //marshalling的解码和编码
                        sc.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingDecoder());
                        sc.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingEncoder());

                        sc.pipeline().addLast(new ClientHandler());
                    }
                });

        //端口
        ChannelFuture cf1 = b.connect("127.0.0.1", 8765).sync();

        //发送java对象
        for (int i = 0;i < 5;i++) {
            Req req = new Req();
            req.setId("" + i);
            req.setName("管儿子" + i);
            req.setRequestMessage("数据信息" + i);

            //发送压缩文件
            String path = System.getProperty("user.dir") + File.separatorChar + "src/main/resources/sources" +  File.separatorChar + "002.jpg";
            System.out.println(path);
            File file = new File(path);
            FileInputStream in = new FileInputStream(file);
            byte[] data = new byte[in.available()];
            in.read(data);
            in.close();
            req.setAttachment(GzipUtils.gzip(data));


            cf1.channel().writeAndFlush(req);
        }


        cf1.channel().closeFuture().sync();
        group.shutdownGracefully();
    }
}
